import AMapLoader from '@amap/amap-jsapi-loader'
import '@amap/amap-jsapi-types'
import { CaretDownOutlined } from '@ant-design/icons'
import { useFullscreen } from 'ahooks'
import { Popover } from 'antd'
import classNames from 'classnames'
import { debounce, isEmpty } from 'lodash-es'
import { useContext, useEffect, useMemo, useRef, useState } from 'react'

//点聚合、街道、建筑 markder
import associationMarkerPng from '@/assets/icons/safeCoGovernance/associationMarker.png'
import carTransportSelectIcon from '@/assets/icons/safeCoGovernance/car-transport-select-icon.png'
import carClusterPng20 from '@/assets/icons/safeCoGovernance/carCluster20.png'
import carClusterPng28 from '@/assets/icons/safeCoGovernance/carCluster28.png'
import carClusterPng39 from '@/assets/icons/safeCoGovernance/carCluster39.png'
import carMakerForNoClusterPng from '@/assets/icons/safeCoGovernance/carMakerForNoCluster.png'
import carMakerStopPng from '@/assets/icons/safeCoGovernance/carMakerStop.png'
import carMakerStopForNoClusterPng from '@/assets/icons/safeCoGovernance/carMakerStopForNoCluster.png'
import carMakerGif from '@/assets/icons/safeCoGovernance/carMarkerGif.gif'
import carMakerZoom20Png from '@/assets/icons/safeCoGovernance/carMarkerZoom20.png'
import carMakerZoom20Gif from '@/assets/icons/safeCoGovernance/carMarkerZoom20Gif.gif'
import enterpriceMarkerPng from '@/assets/icons/safeCoGovernance/enterpriceMarker.png'
import governmentMarkerPng from '@/assets/icons/safeCoGovernance/governmentMarker.png'
import serviceMarkerPng from '@/assets/icons/safeCoGovernance/serviceMarker.png'
// layer icon
import ViewLoading from '@/components/ViewLoading'
import { UIHEIGHT, UIWIDTH } from '@/constant/common'
import { provinceCityDistrictObj } from '@/constant/provinceCityDistrictObj'

import { LoginEnt } from '@/models/LoginEnt'
import { useAppSelector } from '@/redux/store'
import { loginEntSlice } from '@/redux/toolkitSlice/loginEntSlice'
import { splicePlateNum } from '@/utils/compUtils'
import { arrayChunk } from '@/utils/other'
import { useDispatch } from 'react-redux'

import BigScreenContext from '../Context/BigScreenContext'
import DataAnalysis from './Compoments/DataAnalysis'
import WrapperHeader from './Compoments/WrapperHeader'
import LargeScreenLeftContent from './Left'
import type { Tb } from './ModuleTitle'
import { ModuleTitle } from './ModuleTitle'
import OverviewBox from './OverviewBox'
import LargeScreenRightContent from './Right'
import { ContentTsx } from './contentTsx'
import type {
  CarDetail,
  ChartResizeRef,
  IDataAnalysisItem,
  IDataAnalysisType,
  TCurrOrgAddressItem
} from './data'
import {
  getCarsPositionBatch, // mapIconLayer1MockData,

  // mapIconLayerMockData // mapIconLayer2MockData,
  // mapIconLayer3MockData,
  // mapIconLayer4MockData,
  // mapPointLayerMockData // mockPlateNumberListData
  getCurrCarTypeList,
  getCurrOrgCarList,
  getCurrOrgChildAddressList,
  getDataAnalysis
} from './data'
import type {
  AssociationData,
  ICarGeoData,
  IOrgGeoData,
  OrgType,
  SwitchAndIntervalRef
} from './interface'
import { renderMakerItemDom } from './utils'

import { useNavigate } from 'react-router-dom'
import './index.less'
import './module.less'

// initial/switchXiehui/switchCarCluster:点聚合图层 carDisClusterRef.current === undefiend
type CarListRequestType =
  | 'initial'
  | 'zoom'
  | 'interval5'
  | 'switchXiehui'
  | 'siwtchCarType'
  | 'switchCarCluster'

export default function BigScreenBase() {
  const dispatch = useDispatch()
  const navigator = useNavigate()
  const {
    entId: initialEntId,
    entTypeCode,
    entName,
    regionCode,
    operateEntFlag,
    selectedEnt
  } = useAppSelector((state) => {
    // console.log('--state.loginEnt--:', state.loginEnt);
    return state.loginEnt
  })

  const entId =
    selectedEnt && selectedEnt.entId ? selectedEnt.entId : initialEntId

  // console.log('---1屏--entId--:', entId);

  const { onSlideToRight, onSlideToLeft } = useContext(BigScreenContext)
  const LeftContentRef = useRef<SwitchAndIntervalRef>(null)
  const RightContentRef = useRef<SwitchAndIntervalRef>(null)
  const OverviewBoxRef = useRef<SwitchAndIntervalRef>(null)
  const [viewLoading, setViewloading] = useState<boolean>(false)
  //刷新定时器
  const timerRef = useRef<any>(null)
  const [refreshFlag, _fresh] = useState<any>(0)

  const startTimer = () => {
    //开始
    if (timerRef.current) clearInterval(timerRef.current)
    timerRef.current = setInterval(() => {
      if (orgTypeRef.current) {
        _getCurrOrgChildAddressList(
          selectedAssociationKeyRef.current,
          orgTypeRef.current
        ) //当前协会下的下级组织地址列表
      }
      isChoicingCarClusterRef.current = true
      setChoicingCarCluster(true)
      _getCurrOrgCarList(
        selectedAssociationKeyRef.current,
        carTransportTypesRef.current,
        'interval5'
      ).then(() => {
        // 当前协会车辆列表
        isChoicingCarClusterRef.current = false
        setTimeout(() => {
          setChoicingCarCluster(false)
        }, 5000)
      })
      _getDataAnalysis(
        dataAnalysisTypeRef.current,
        selectedAssociationKeyRef.current
      ) //新增数据分析
      //左侧 司机数据分析 数字翻牌
      LeftContentRef.current!.intervalRefresh()
      //右侧 车辆数据分析、安全教育 数字翻牌
      RightContentRef.current!.intervalRefresh()
      //中间 组织数据分析 数字翻牌
      OverviewBoxRef.current!.intervalRefresh()
      _fresh(Math.random())
    }, 300000) //300s = 5分钟
  }

  const clearTimer = () => {
    //清除
    if (timerRef.current) {
      clearTimeout(timerRef.current)
    }
    clearDataAnalysInterval()
  }

  //地图
  const AMapRef = useRef<any>()
  const LocaRef = useRef<any>()
  const [weatherPlugin, setWeatherPlugin] = useState<any>()
  const prevZoomRef = useRef<number>(0)

  // 省[5,9] 点可视化
  const carPointLayerRef = useRef<any>()
  const orgPointLayerRef = useRef<any>()

  const carDisClusterRef = useRef<any>() //点聚合图层
  const carDetailListRef = useRef<CarDetail[]>([]) //车辆位置信息列表
  const carMarkersRef = useRef<any[]>([]) //14-21 carMarker
  const carInfoWindowRef = useRef<any>()
  const [isCarCluster, setIsCarCluster] = useState<boolean>(true) //car 默认展示聚合模式
  const isCarClusterRef = useRef<boolean>(true)
  const isChoicingCarClusterRef = useRef<boolean>(false) //防止频繁点击
  const [choicingCarCluster, setChoicingCarCluster] = useState<boolean>(true)
  const massMarkersRef = useRef<any>() //非聚合模式下的海量点

  const orgMarkersRef = useRef<any[]>([]) //12-21 orgMarker
  const orgListRef = useRef<TCurrOrgAddressItem[]>([])

  const largeScreenContainer = useRef<HTMLDivElement>(null)
  const containerWrapperRef = useRef<HTMLDivElement>(null)
  const [domScale, setDomScale] = useState<number>(1)

  //全屏显示 { pageFullscreen: true }
  const [isFullscreen, { toggleFullscreen, enterFullscreen }] =
    useFullscreen(largeScreenContainer)
  const isFullscreenRef = useRef<boolean>(isFullscreen)

  // 标题协会切换
  const [selectedAssociationItem, setSelectedAssociationItem] =
    useState<AssociationData>({
      key: entId,
      label: '',
      regionCode,
      operateEntFlag,
      regionCodeValue: ''
    })
  const selectedAssociationKeyRef = useRef<string>(entId)

  const [carTransportOriginTypeList, setCarTransportOriginTypeList] = useState<
    {
      label: string
      value: string
      key: string
    }[]
  >([])

  //--车辆运输类型--
  useEffect(() => {
    getCurrCarTypeList({ entId: selectedAssociationKeyRef.current }).then(
      (res) => {
        if (res.suc) {
          const carTypeList = res.data ?? []
          const updatedCarTypeList = carTypeList.map((v) => {
            return { label: v.name, value: v.value, key: v.code }
          })
          setCarTransportOriginTypeList(updatedCarTypeList)
          setCarTransportTypeItems(
            carTypeList.map((v) => {
              return { label: v.name, key: v.value }
            })
          )
          carTransportTypesRef.current = carTypeList.map((v) => v.value)
        } else {
          setCarTransportOriginTypeList([])
        }
      }
    )
  }, [selectedAssociationItem.key])

  const [carTransportTypeItems, setCarTransportTypeItems] = useState<
    { key: string; label: string }[]
  >([])
  const carTransportTypesRef = useRef<string[]>([])

  const carDropDownLableShow = useMemo<React.ReactNode>(() => {
    if (!carTransportTypeItems.length) {
      return '已隐藏全部车辆'
    } else if (
      carTransportTypeItems.length === carTransportOriginTypeList.length
    ) {
      return '全部车辆'
    } else if (carTransportTypeItems.length === 1) {
      return carTransportTypeItems[0].label
    } else {
      return (
        <span>
          包含<span className="count">{carTransportTypeItems.length}</span>
          类车辆
        </span>
      )
    }
  }, [carTransportTypeItems, carTransportOriginTypeList])

  //组织切换
  const [orgType, setOrgType] = useState<OrgType>('-1')
  const orgTypeRef = useRef<OrgType>('-1')
  const isChoiceingOrgTypRef = useRef<boolean>(false)

  //新增数据分析
  const [dataAnalysisType, setDataAnalysisType] =
    useState<IDataAnalysisType>('half')
  const dataAnalysisTypeRef = useRef<IDataAnalysisType>('half')
  const [dataAnalysisList, setDataAnalysisList] = useState<IDataAnalysisItem[]>(
    []
  )
  const DataAnalysisCompRef = useRef<ChartResizeRef>(null)
  const echartsLegends = useMemo<{ color: string; text: string }[]>(
    () => [
      { color: '#40E6AE', text: '组织' },
      { color: '#5FA6F5', text: '从业人员' },
      { color: '#F66E2C', text: '车辆' }
    ],
    []
  )
  const analysTypeIntervalRef = useRef<any>()
  const analysTitleTab = useMemo<{ name: string; value: IDataAnalysisType }[]>(
    () => [
      // { name: "年", value: "y" },
      // { name: "月", value: "m" },
      // { name: "日", value: "d" },
      { name: '近一月', value: 'd' },
      { name: '近半月', value: 'half' },
      { name: '近一周', value: 'week' }
    ],
    []
  )
  //---切换车辆类型----
  //全选操作
  const choiceAllCarType = () => {
    isChoicingCarClusterRef.current = true
    setChoicingCarCluster(true)
    clearTimer()
    if (
      carTransportTypesRef.current.length &&
      carTransportTypesRef.current.length === carTransportOriginTypeList.length
    ) {
      //取消选中
      carTransportTypesRef.current = []
      setCarTransportTypeItems([])
    } else {
      setCarTransportTypeItems(
        carTransportOriginTypeList.map((v) => {
          return { label: v.label, key: v.value }
        })
      )
      carTransportTypesRef.current = carTransportOriginTypeList.map(
        (v) => v.value
      )
    }

    _getCurrOrgCarList(
      selectedAssociationKeyRef.current,
      carTransportTypesRef.current,
      'siwtchCarType'
    ).finally(() => {
      // 当前协会车辆列表
      startTimer()
      isChoicingCarClusterRef.current = false
      setTimeout(() => {
        setChoicingCarCluster(false)
      }, 5000)
    })
  }

  //选中某个
  const choiceCarType = (keyParam: string) => {
    isChoicingCarClusterRef.current = true
    setChoicingCarCluster(true)
    clearTimer()
    const existIndex = carTransportTypesRef.current.findIndex(
      (itemKey) => itemKey === keyParam
    )
    let tempTypeItems = carTransportTypeItems
    if (existIndex > -1) {
      //取消选中
      carTransportTypesRef.current.splice(existIndex, 1)
      tempTypeItems.splice(existIndex, 1)
    } else {
      //选中
      const typeItem = carTransportOriginTypeList.find(
        (typeItem) => typeItem.value === keyParam
      )
      if (!typeItem) {
        throw new Error(`key = 【${keyParam}】的车辆类型没有获取到`)
      }
      const { value, label } = typeItem
      if (
        carTransportTypesRef.current.length &&
        carTransportTypesRef.current.length ===
          carTransportOriginTypeList.length - 1
      ) {
        //全部选中
        tempTypeItems = carTransportOriginTypeList.map((v) => {
          return { label: v.label, key: v.value }
        })
        carTransportTypesRef.current = carTransportOriginTypeList.map(
          (v) => v.value
        )
      } else {
        tempTypeItems.push({ key: value, label })
        carTransportTypesRef.current.push(value)
      }
    }
    setCarTransportTypeItems([...tempTypeItems])
    _getCurrOrgCarList(
      selectedAssociationKeyRef.current,
      carTransportTypesRef.current,
      'siwtchCarType'
    ).finally(() => {
      // 当前协会车辆列表
      startTimer()
      isChoicingCarClusterRef.current = false
      setTimeout(() => {
        setChoicingCarCluster(false)
      }, 5000)
    })
  }

  const carTypePopverContent = useMemo<React.ReactElement>(() => {
    return (
      <>
        <div className="pop-list-item  item-all" onClick={choiceAllCarType}>
          <div
            className={classNames('item-checkbox', {
              ['checked']:
                carTransportTypeItems.length &&
                carTransportTypeItems.length ===
                  carTransportOriginTypeList.length
            })}
          ></div>
          <p className="item-title">全部车辆</p>
        </div>
        <ul className="pop-list">
          {carTransportOriginTypeList.map((typeItem) => (
            <li
              className="pop-list-item"
              key={typeItem.value}
              onClick={() => {
                choiceCarType(typeItem.key)
              }}
            >
              <div
                className={classNames('item-checkbox', {
                  ['checked']:
                    carTransportTypeItems.findIndex(
                      (item) => item.key === typeItem.key
                    ) > -1
                      ? true
                      : false
                })}
              ></div>
              <p className="item-title">{typeItem.label}</p>
            </li>
          ))}
        </ul>
      </>
    )
  }, [carTransportOriginTypeList, carTransportTypeItems, domScale])

  //聚合数据切换
  const carClusterOnChange = () => {
    if (isChoicingCarClusterRef.current) return
    isChoicingCarClusterRef.current = true
    setChoicingCarCluster(true)
    isCarClusterRef.current = !isCarCluster
    setIsCarCluster(!isCarCluster)
    clearTimer()
    AMapRef.current.remove(carMarkersRef.current) //清除普通marker
    if (isCarCluster) {
      //从聚合--非聚合
      if (carInfoWindowRef.current) {
        //关闭信息窗体
        carInfoWindowRef.current.close()
      }
      if (orgTypeRef.current) {
        AMapRef.current.remove(orgMarkersRef.current) //清除marker
        orgMarkersRef.current = []
        orgListRef.current = []
        orgTypeRef.current = undefined
        setOrgType(undefined)
      }

      if (carPointLayerRef.current) {
        const pointGeo = new window.Loca.GeoJSONSource({
          data: {}
        })
        carPointLayerRef.current.setSource(pointGeo)
      }
      if (orgPointLayerRef.current) {
        const pointGeo = new window.Loca.GeoJSONSource({
          data: {}
        })
        orgPointLayerRef.current.setSource(pointGeo)
      }

      if (carDisClusterRef.current) {
        carDisClusterRef.current.setData([])
        carDisClusterRef.current.setMap(null) //清除点聚合图层
        carDisClusterRef.current = undefined
      }
      const moveingCarMarkers: any[] = []
      if (carDetailListRef.current.length) {
        if (carMarkersRef.current.length) {
          //14-21
          carMarkersRef.current.forEach((markerInstance) => {
            const { gpsStats } = markerInstance.getExtData()
            if (gpsStats === 1) {
              const iconInstance = new AMap.Icon({
                size: [12, 12],
                image: carMakerForNoClusterPng,
                imageSize: [12, 12]
              })
              markerInstance.setIcon(iconInstance)
              moveingCarMarkers.push(markerInstance)
            }
          })
        } else {
          //5-12、12-14
          for (let i = 0; i < carDetailListRef.current.length; i++) {
            const { lnglat, directDegree, gpsStats, plateNumber } =
              carDetailListRef.current[i]
            if (gpsStats === 1) {
              const marker = new AMap.Marker({
                zIndex: 10,
                angle: directDegree,
                anchor: 'center',
                // map: AMapRef.current,
                position: lnglat,
                extData: {
                  plateNumber,
                  gpsStats
                }
              })
              marker.on('click', carMarkerClick)
              const iconInstance = new AMap.Icon({
                size: [12, 12],
                image: carMakerForNoClusterPng,
                imageSize: [12, 12]
              })
              marker.setIcon(iconInstance)
              moveingCarMarkers.push(marker)
            }
          }
        }
        carMarkersRef.current = moveingCarMarkers
        const boundsMarkers = _getBoundingsMarkers(carMarkersRef.current)
        AMapRef.current.add(boundsMarkers)

        //海量点
        if (!massMarkersRef.current) {
          const moMovingCarList = carDetailListRef.current.filter(
            (carItem) => carItem.gpsStats !== 1
          )
          massMarkersRef.current = new AMap.MassMarks(moMovingCarList as any, {
            zIndex: 9,
            cursor: 'default',
            style: {
              url: carMakerStopForNoClusterPng,
              anchor: new AMap.Pixel(-5, -5),
              size: new AMap.Size(12, 12)
            } as any
          })
          massMarkersRef.current.setMap(AMapRef.current)
        }

        setTimeout(() => {
          isChoicingCarClusterRef.current = false
          setChoicingCarCluster(false)
        }, 8000)
      } else {
        isChoicingCarClusterRef.current = false
        setChoicingCarCluster(false)
      }
    } else {
      //从非聚合--聚合
      carDetailListRef.current = []
      carMarkersRef.current = []
      if (massMarkersRef.current) {
        massMarkersRef.current.clear()
        massMarkersRef.current.setMap(null)
        massMarkersRef.current = undefined
      }

      if (orgTypeRef.current) {
        _getCurrOrgChildAddressList(
          selectedAssociationItem.key,
          orgTypeRef.current
        )
      }

      _getCurrOrgCarList(
        selectedAssociationItem.key,
        carTransportTypesRef.current,
        'switchCarCluster'
      ).finally(() => {
        // 当前协会车辆列表
        startTimer()
        setTimeout(() => {
          isChoicingCarClusterRef.current = false
          setChoicingCarCluster(false)
        }, 5000)
      })
    }
  }

  //大屏 等比缩放
  function _setWrapperSize(largeScreenDom: HTMLDivElement) {
    const { clientWidth, clientHeight } = largeScreenDom ?? {}
    if (!clientWidth || !clientHeight) {
      //切换页签时，clientWidth === 0，clientHeight===0
      setTimeout(() => {
        _setWrapperSize(largeScreenDom)
      }, 1000)
      return
    }

    let widthScale, heightScale

    if (isFullscreenRef.current) {
      widthScale = window.innerWidth / UIWIDTH
      heightScale = window.innerWidth / UIHEIGHT
    } else if (clientWidth && clientHeight) {
      widthScale = clientWidth / UIWIDTH
      heightScale = clientHeight / UIHEIGHT
    }

    const finalScale =
      widthScale && heightScale ? Math.min(widthScale, heightScale) : 1 //取小者，保持等比缩放，dom尺寸/内容不变形
    setDomScale(finalScale)
    containerWrapperRef.current!.style.width = UIWIDTH * finalScale + 'px'
    containerWrapperRef.current!.style.height = UIHEIGHT * finalScale + 'px'

    // containerWrapperRef.current!.style.transform = `scale(${finalScale}) translate(-50%, -50%)`
  }

  //设置地图中心
  function _setMapCenter(regionCode: string | undefined) {
    if (regionCode) {
      const centerStr = (provinceCityDistrictObj[regionCode] ?? {}).center
      if (centerStr) {
        const center = centerStr.split(',')
        const centerLnglat = new AMap.LngLat(
          Number(center[0]),
          Number(center[1])
        )
        AMapRef.current.setCenter(centerLnglat)
      }
    }
  }

  function _resizeCanvas() {
    //地图缩放
    if (AMapRef.current) {
      AMapRef.current.resize()
    }
    //新增数据分析 echarts缩放
    DataAnalysisCompRef.current?.resize()
    //Left
    LeftContentRef.current?.resize?.()
    //Right
    RightContentRef.current?.resize?.()
  }

  //全屏操作 也会触发window.resize()
  const debounceResize = debounce(() => {
    // console.log("--debounceResize--isFullscreen--:", isFullscreen)
    _setWrapperSize(largeScreenContainer.current!)
    _resizeCanvas()
  }, 500)

  useEffect(() => {
    isFullscreenRef.current = isFullscreen
    window.addEventListener('resize', debounceResize) //初始化的时候不执行
    return () => {
      window.removeEventListener('resize', debounceResize)
    }
  }, [isFullscreen])

  //协会切换
  const handleAssociationClick = (associationItem: AssociationData) => {
    const key = associationItem.key
    // console.log("--handleAssociationClick--key--:", key)
    if (selectedAssociationKeyRef.current === key) return
    dispatch(
      loginEntSlice.actions.updateSelectedEnt(
        new LoginEnt({
          ...associationItem,
          entId: key,
          entName: associationItem.label
        })
      )
    )
    isChoicingCarClusterRef.current = true
    setChoicingCarCluster(true)
    clearDataAnalysInterval()
    clearTimer()

    setSelectedAssociationItem(associationItem)
    selectedAssociationKeyRef.current = key

    //左侧 司机数据分析 数字翻牌
    if (LeftContentRef.current) {
      LeftContentRef.current.switchAssociation(key)
    }
    if (RightContentRef.current) {
      //右侧 车辆数据分析、安全教育 数字翻牌
      RightContentRef.current.switchAssociation(key)
    }
    if (OverviewBoxRef.current) {
      //中间 组织数据分析 数字翻牌
      OverviewBoxRef.current.switchAssociation(key)
    }

    //重置地图中心
    _setMapCenter(associationItem.regionCode)

    _getDataAnalysis(dataAnalysisTypeRef.current, key).then(() => {
      //新增数据分析
      startDataAnalysInterval()
    })

    if (carPointLayerRef.current) {
      //car点可视化
      const pointGeo = new window.Loca.GeoJSONSource({
        data: {} //mapPointLayerMockData
      })
      carPointLayerRef.current.setSource(pointGeo)
    }

    if (orgPointLayerRef.current) {
      //org点可视化
      const pointGeo = new window.Loca.GeoJSONSource({
        data: {} //mapPointLayerMockData
      })
      orgPointLayerRef.current.setSource(pointGeo)
    }

    if (carDisClusterRef.current) {
      //car 点聚合
      carDisClusterRef.current.setData([])
      carDisClusterRef.current.setMap(null) //清除点聚合图层
      carDisClusterRef.current = undefined
    }
    if (orgTypeRef.current) {
      _getCurrOrgChildAddressList(key, orgTypeRef.current) //当前协会下的下级组织地址列表
    }
    _getCurrOrgCarList(
      key,
      carTransportTypesRef.current,
      'switchXiehui'
    ).finally(() => {
      isChoicingCarClusterRef.current = false
      setTimeout(() => {
        setChoicingCarCluster(false)
      }, 5000)
      // 当前协会车辆列表
      startTimer()
    })
  }

  //批量获取车辆gps（经纬度）详情列表
  function _getCarPositionBatch(
    plateNumberList: string[]
  ): Promise<CarDetail[]> {
    if (!plateNumberList || !plateNumberList.length) {
      return Promise.reject('plateNumberList is empty')
    }
    let chunkPalteNumberList = arrayChunk(plateNumberList, 200)
    chunkPalteNumberList = chunkPalteNumberList.filter(
      (listItems) => listItems && listItems.length
    )
    const carsPositionPromises = chunkPalteNumberList.map((listItems) => {
      const plateNumberStr = listItems.join(',')
      return getCarsPositionBatch({ vehicle: plateNumberStr })
    })
    return new Promise((resolve, reject) => {
      Promise.all(carsPositionPromises)
        .then((resList) => {
          const resCarDetailList = (resList || []).reduce(
            (prev: CarDetail[], curr: any, index, array: any[]) => {
              const { data } = curr
              if (data && data.length) {
                const validData = data
                  .filter(
                    (dataItem: CarDetail) =>
                      dataItem &&
                      dataItem.addressDict &&
                      typeof dataItem.longitude === 'number' &&
                      typeof dataItem.latitude === 'number' &&
                      dataItem.plateNumber
                  )
                  .map((mapDataItem: CarDetail) => {
                    const { provinceName, cityName, name } =
                      mapDataItem.addressDict!
                    return {
                      ...mapDataItem,
                      provinceName,
                      cityName,
                      districtName: name,
                      lnglat: [mapDataItem.longitude, mapDataItem.latitude]
                    }
                  })
                prev.push(...validData)
              }
              return prev
            },
            []
          )

          resolve(resCarDetailList)
        })
        .catch((errorList) => {
          resolve([])
        })
    })
  }

  //当前协会下的车辆列表
  function _getCurrOrgCarList(
    entIdParam: string,
    carTransportTypes: string[],
    requestType: CarListRequestType
  ) {
    const transportCode = !carTransportTypes.length
      ? undefined
      : carTransportTypes.join(',')
    if (carInfoWindowRef.current) {
      //关闭信息窗体
      carInfoWindowRef.current.close()
    }
    return getCurrOrgCarList({ entId: entIdParam, transportCode })
      .then((res) => {
        if (!AMapRef.current) {
          console.error(
            `--_getCurrOrgCarList--requestType:【${requestType}】--AMapRef不存在--`
          )
          return
        }
        const { data = [] } = res
        // console.log("--getCurrOrgCarList--data--:", data)
        const plateNumberList = data.map((dataItem) => dataItem.carBrand)
        // const plateNumberList = mockPlateNumberListData
        if (isEmpty(plateNumberList)) {
          if (carPointLayerRef.current) {
            const pointGeo = new window.Loca.GeoJSONSource({
              data: {} //mapPointLayerMockData
            })
            carPointLayerRef.current.setSource(pointGeo)
          }
          if (carDisClusterRef.current) {
            carDisClusterRef.current.setData([])
            carDisClusterRef.current.setMap(null) //清除点聚合图层
            carDisClusterRef.current = undefined
          }

          AMapRef.current.remove(carMarkersRef.current) //清除普通marker
          carDetailListRef.current = []
          carMarkersRef.current = []

          if (massMarkersRef.current) {
            massMarkersRef.current.clear()
            massMarkersRef.current.setMap(null)
            massMarkersRef.current = undefined
          }

          return
        }
        //requestType === 'initial','interval5','siwtchXiehui','siwtchCarType'时清除普通marker
        AMapRef.current.remove(carMarkersRef.current)
        carDetailListRef.current = []
        carMarkersRef.current = []
        if (massMarkersRef.current) {
          massMarkersRef.current.clear()
          massMarkersRef.current.setMap(null)
          massMarkersRef.current = undefined
        }
        return _getCarPositionBatch(plateNumberList)
          .then((carDetailList) => {
            // console.log("--getCarPositionBatch--carDetailList--:", carDetailList)
            carDetailListRef.current = carDetailList

            if (isCarClusterRef.current) {
              //聚合模式
              // 省[5,12] 添加点图层-车
              const features: ICarGeoData['features'] = carDetailList.map(
                (listItem) => {
                  const { longitude, latitude, plateNumber } = listItem
                  return {
                    type: 'Feature',
                    properties: {
                      plateNumber
                    },
                    geometry: {
                      type: 'Point',
                      coordinates: [longitude, latitude]
                    }
                  }
                }
              )
              const mapCarPointData: ICarGeoData = {
                type: 'FeatureCollection',
                features
              }

              //  carPointLayerRef.current.remove(); //从地图上清除图层,清除之后必须重新创建
              if (!carPointLayerRef.current) {
                console.error(
                  `--_getCurrOrgCarList--requestType:【${requestType}】--carPointLayerRef.current不存在--`
                )
                return
              }
              const pointGeo = new window.Loca.GeoJSONSource({
                data: { ...mapCarPointData } // mapPointLayerMockData,   mapMockData,
              })
              carPointLayerRef.current.setSource(pointGeo)
              // 注：更新代码时，如下代码会导致报错catch

              _loadCarMarker(carDetailList, requestType)
            } else {
              if (carPointLayerRef.current) {
                const pointGeo = new window.Loca.GeoJSONSource({
                  data: {}
                })
                carPointLayerRef.current.setSource(pointGeo)
              }

              if (carDisClusterRef.current) {
                carDisClusterRef.current.setData([])
                carDisClusterRef.current.setMap(null) //清除点聚合图层
                carDisClusterRef.current = undefined
              }
              _laodCarMarkerForNoCluster(carDetailList)
            }
          })
          .catch((err) => {
            if (carPointLayerRef.current) {
              const pointGeo = new window.Loca.GeoJSONSource({
                data: {}
              })
              carPointLayerRef.current.setSource(pointGeo)
            }

            if (carDisClusterRef.current) {
              carDisClusterRef.current.setData([])
              carDisClusterRef.current.setMap(null) //清除点聚合图层
              carDisClusterRef.current = undefined
            }
            AMapRef.current.remove(carMarkersRef.current) //清除marker
            carMarkersRef.current = []
            carDetailListRef.current = []
            if (massMarkersRef.current) {
              massMarkersRef.current.clear()
              massMarkersRef.current.setMap(null)
              massMarkersRef.current = undefined
            }
          })
      })
      .catch((err) => {
        console.error('--BigScreenBase--getCurrOrgCarList--err--:', err)
      })
  }

  //当前协会下的下级组织地址列表
  function _getCurrOrgChildAddressList(
    entIdParam: string,
    orgTypeParam: OrgType
  ) {
    const orgType = orgTypeParam === '-1' ? undefined : orgTypeParam
    if (AMapRef.current && orgMarkersRef.current.length) {
      AMapRef.current.remove(orgMarkersRef.current) //清除marker
      orgMarkersRef.current = []
      orgListRef.current = []
    }
    if (orgPointLayerRef.current) {
      const pointGeo = new window.Loca.GeoJSONSource({
        data: {}
      })
      orgPointLayerRef.current.setSource(pointGeo)
    }
    return getCurrOrgChildAddressList({ entId: entIdParam, orgType })
      .then((res) => {
        if (!AMapRef.current) {
          throw new Error('--_getCurrOrgChildAddressList--AMapRef不存在--')
        }
        const { data = [] } = res

        //12-21
        const orgList: TCurrOrgAddressItem[] = []
        data.forEach((orgItem) => {
          let tempObj
          const { adCode, longitude, latitude, regionCode } = orgItem
          if (typeof longitude === 'number' && typeof latitude === 'number') {
            const lnglat: [number, number] = [longitude, latitude]
            tempObj = { ...orgItem, lnglat }
          } else if (regionCode && regionCode.length === 6) {
            const { center: centerStr } = provinceCityDistrictObj[adCode!] ?? {}
            if (centerStr) {
              const center = centerStr.split(',')
              const tempLongitude = Number(center[0])
              const tempLatitude = Number(center[1])
              tempObj = {
                ...orgItem,
                longitude: tempLongitude,
                latitude: tempLatitude,
                lnglat: [tempLongitude, tempLatitude]
              }
            }
          }
          if (tempObj) {
            orgList.push(tempObj as TCurrOrgAddressItem)
          }
        })
        orgListRef.current = orgList

        if (isCarClusterRef.current) {
          //聚合模式
          _loadOrgMarker(orgList)

          //5-12
          const features: IOrgGeoData['features'] = orgList.map((listItem) => {
            const { longitude, latitude, entName } = listItem
            return {
              type: 'Feature',
              properties: {
                entName
              },
              geometry: {
                type: 'Point',
                coordinates: [longitude!, latitude!]
              }
            }
          })
          const mapOrgPointData: IOrgGeoData = {
            type: 'FeatureCollection',
            features
          }

          const pointGeo = new window.Loca.GeoJSONSource({
            data: { ...mapOrgPointData }
          })
          orgPointLayerRef.current.setSource(pointGeo)
        } else {
          if (orgPointLayerRef.current) {
            const pointGeo = new window.Loca.GeoJSONSource({
              data: {}
            })
            orgPointLayerRef.current.setSource(pointGeo)
          }
          _laodOrgMarkerForNoCluster(orgList)
        }
      })
      .catch((err) => {
        AMapRef.current.remove(orgMarkersRef.current) //清除marker
        orgMarkersRef.current = []
        orgListRef.current = []
        if (orgPointLayerRef.current) {
          const pointGeo = new window.Loca.GeoJSONSource({
            data: {}
          })
          orgPointLayerRef.current.setSource(pointGeo)
        }
        console.error(
          '--BigScreenBase--getCurrOrgChildAddressList--err--:',
          err
        )
      })
  }

  //-----点击切换组织类型----
  const handleOrgTypeClick = (choicedOrgType: OrgType | undefined) => {
    if (isChoiceingOrgTypRef.current) return
    isChoiceingOrgTypRef.current = true
    setOrgType(choicedOrgType)
    orgTypeRef.current = choicedOrgType

    if (choicedOrgType !== undefined) {
      clearTimer()
      _getCurrOrgChildAddressList(
        selectedAssociationKeyRef.current,
        choicedOrgType
      ).finally(() => {
        //地址列表
        startTimer()
        isChoiceingOrgTypRef.current = false
      })
    } else {
      AMapRef.current.remove(orgMarkersRef.current) //清除marker
      orgMarkersRef.current = []
      orgListRef.current = []
      isChoiceingOrgTypRef.current = false
      if (orgPointLayerRef.current) {
        const pointGeo = new window.Loca.GeoJSONSource({
          data: {}
        })
        orgPointLayerRef.current.setSource(pointGeo)
      }
    }
  }

  //------------------------点聚合marker------------------------
  //聚合点
  function _renderCarClusterMarker(context: any) {
    // console.log('--点聚合--context--:', context)
    const { marker, count } = context
    let clusterPointDom
    if (count < 50) {
      clusterPointDom = renderMakerItemDom(count, carClusterPng20, 20)
    } else if (count >= 50 && count < 150) {
      clusterPointDom = renderMakerItemDom(count, carClusterPng28, 28)
    } else {
      clusterPointDom = renderMakerItemDom(count, carClusterPng39, 39)
    }
    marker.setAnchor('center')
    marker.setzIndex(12)
    marker.setCursor('pointer')
    marker.setContent(clusterPointDom)
    marker.on('click', (e: any) => {
      let curZoom = AMapRef.current.getZoom()
      if (curZoom < 14) {
        curZoom += 1
      }
      AMapRef.current.setZoomAndCenter(curZoom, e.lnglat)
    })
  }

  //非聚合点
  function _renderCarMarker(context: any) {
    // console.log('--非点聚合--context--:', context);
    const { data, marker, count } = context

    const { directDegree, gpsStats } = data[0] ?? {}
    const currSize: any = gpsStats === 1 ? [44, 44] : [20, 20]
    const iconInstance = new AMap.Icon({
      size: currSize,
      image: gpsStats === 1 ? carMakerGif : carMakerStopPng,
      imageSize: currSize
    })
    marker.setAngle(directDegree)
    marker.setAnchor('center')
    marker.setIcon(iconInstance)
    marker.setzIndex(11)
    marker.setCursor('default')
  }

  function _getCarMarkerIconInstance(
    gpsStats: 1 | 2 | 3 = 3,
    currZoom: number
  ) {
    let iconInstance
    if (currZoom >= 14 && currZoom < 18) {
      const currSize: any = gpsStats === 1 ? [44, 44] : [20, 20]
      iconInstance = new AMap.Icon({
        size: currSize,
        image: gpsStats === 1 ? carMakerGif : carMakerStopPng,
        imageSize: currSize
      })
    } else {
      const currSize: any = gpsStats === 1 ? [55, 55] : [16, 34]
      iconInstance = new AMap.Icon({
        size: currSize,
        image: gpsStats === 1 ? carMakerZoom20Gif : carMakerZoom20Png,
        imageSize: currSize
      })
    }
    return iconInstance
  }

  //获取当前地图可视区域范围内的点
  function _getBoundingsMarkers(markerInstanceList: any[]): any[] {
    const bounds = AMapRef.current.getBounds() //getBounds：获取当前地图可视区域范围
    const boundMarkers = markerInstanceList.filter((markerInstance: any) => {
      const { lng, lat } = markerInstance.getPosition()
      return bounds.contains(new AMap.LngLat(lng, lat))
    })
    // console.log("--地图可视区域范围点个数boundMarkers.length--:", boundMarkers.length)
    return boundMarkers
  }

  //carMaker点击
  function carMarkerClick(event: MouseEvent) {
    const targetMaker = event.target as any
    if (!targetMaker) return
    const position = targetMaker.getPosition()
    const { plateNumber } = targetMaker.getExtData()
    const windowInfoContent =
      '<span style="padding:4px 8px;border-radius: 2px;border: 1px solid;font-size: 14px;color: #FFFFFF;' +
      'background: linear-gradient( 180deg, rgba(0,0,0,0.16) 0%, rgba(0,0,0,0.32) 100%), linear-gradient( 180deg, rgba(246,110,44,0.04) 0%, rgba(0,0,0,0) 100%);' +
      'border-image: linear-gradient(180deg, rgba(255, 255, 255, 0.24), rgba(255, 255, 255, 0.12)) 1 1;backdrop-filter: blur(8px);">' +
      splicePlateNum(plateNumber) +
      '</span>'
    if (!carInfoWindowRef.current) {
      carInfoWindowRef.current = new AMap.InfoWindow({
        anchor: 'middle-left',
        isCustom: true,
        content: windowInfoContent,
        offset: new AMap.Pixel(15, 0)
      })
    } else {
      carInfoWindowRef.current.setContent(windowInfoContent)
    }
    carInfoWindowRef.current.open(AMapRef.current, position)
  }

  //非聚合模式下
  //car 普通点加载
  function _laodCarMarkerForNoCluster(carDetailList: CarDetail[]) {
    const currZoom = AMapRef.current.getZoom()
    prevZoomRef.current = currZoom
    if (!carMarkersRef.current.length) {
      const tempCarMarkers: any[] = []
      for (let i = 0; i < carDetailList.length; i++) {
        const { lnglat, directDegree, gpsStats, plateNumber } = carDetailList[i]
        if (gpsStats === 1) {
          const marker = new AMap.Marker({
            zIndex: 10,
            angle: directDegree,
            anchor: 'center',
            // map: AMapRef.current,
            position: lnglat,
            extData: {
              plateNumber,
              gpsStats
            }
          })
          marker.on('click', carMarkerClick)
          const iconInstance = new AMap.Icon({
            size: [12, 12],
            image: carMakerForNoClusterPng,
            imageSize: [12, 12]
          })
          marker.setIcon(iconInstance)
          tempCarMarkers.push(marker)
        }
      }
      carMarkersRef.current = tempCarMarkers
      const boundsMarkers = _getBoundingsMarkers(tempCarMarkers)

      AMapRef.current.add(boundsMarkers)
    } else {
      AMapRef.current.remove(carMarkersRef.current)
      const carBoundMarkers = _getBoundingsMarkers(carMarkersRef.current)
      AMapRef.current.add(carBoundMarkers)
    }

    if (!massMarkersRef.current) {
      const moMovingCarList = carDetailListRef.current.filter(
        (carItem) => carItem.gpsStats !== 1
      )
      massMarkersRef.current = new AMap.MassMarks(moMovingCarList as any, {
        zIndex: 9,
        cursor: 'default',
        style: {
          url: carMakerStopForNoClusterPng,
          anchor: new AMap.Pixel(-5, -5),
          size: new AMap.Size(12, 12)
        } as any
      })
      massMarkersRef.current.setMap(AMapRef.current)
    }
  }

  function _loadOrgMarkerCommon(orgList: TCurrOrgAddressItem[]) {
    let tempOrgMarkers: any[] = []
    if (!orgMarkersRef.current.length) {
      tempOrgMarkers = []
      for (let i = 0; i < orgList.length; i++) {
        const { orgType, lnglat } = orgList[i]
        const marker = new AMap.Marker({
          zIndex: 13,
          anchor: 'bottom-center',
          position: lnglat,
          cursor: 'default'
        })
        let imgPath
        if (orgType === '1') {
          imgPath = governmentMarkerPng
        } else if (orgType === '2') {
          imgPath = associationMarkerPng
        } else if (orgType === '3') {
          imgPath = enterpriceMarkerPng
        } else if (orgType === '4') {
          imgPath = serviceMarkerPng
        }
        const iconInstance = new AMap.Icon({
          size: [17, 22],
          image: imgPath,
          imageSize: [17, 22]
        })
        marker.setIcon(iconInstance)
        tempOrgMarkers.push(marker)
      }
      orgMarkersRef.current = tempOrgMarkers
    } else {
      tempOrgMarkers = orgMarkersRef.current
      AMapRef.current.remove(orgMarkersRef.current)
    }
    const boundsMarkers = _getBoundingsMarkers(tempOrgMarkers)
    AMapRef.current.add(boundsMarkers)
  }

  // org 点加载
  function _laodOrgMarkerForNoCluster(orgList: TCurrOrgAddressItem[]) {
    const currZoom = AMapRef.current.getZoom()
    prevZoomRef.current = currZoom
    _loadOrgMarkerCommon(orgList)
  }

  //聚合模式下
  //12-14 car点加载
  //14-18
  //18-21
  function _loadCarMarker(
    carDetailList: CarDetail[],
    requestType: CarListRequestType
  ) {
    const currZoom = AMapRef.current.getZoom()

    if (currZoom < 12) {
      prevZoomRef.current = currZoom
    }

    if (currZoom >= 12 && currZoom < 14) {
      if (!carDisClusterRef.current) {
        //requestType === 'siwtchXiehui','initial'
        prevZoomRef.current = currZoom
        carDisClusterRef.current = new (AMap as any).MarkerCluster(
          AMapRef.current,
          carDetailList,
          {
            gridSize: 50, //数据聚合计算时网格的像素大小 默认60
            maxZoom: 14,
            renderClusterMarker: _renderCarClusterMarker,
            renderMarker: _renderCarMarker
          }
        )
      } else if (
        (requestType === 'zoom' &&
          (prevZoomRef.current < 12 || prevZoomRef.current >= 14)) ||
        requestType === 'interval5' ||
        requestType === 'siwtchCarType'
      ) {
        //滑出范围之外，再滑回来、5分钟，切换car类型
        prevZoomRef.current = currZoom
        carDisClusterRef.current.setData(carDetailList)
        // carDisClusterRef.current.setMap(AMapRef.current)
      }
    } else if (carDisClusterRef.current) {
      carDisClusterRef.current.setData([])
      // carDisClusterRef.current.setMap(null) //清除点聚合图层,清除完之后再进来setMap(AMapRef.current) 会导致无法按照距离点聚合了
    }

    if (currZoom >= 14 && currZoom < 21) {
      //requestType === 'initial','interval5','siwtchXiehui','siwtchCarType'
      prevZoomRef.current = currZoom

      if (!carMarkersRef.current.length) {
        const tempCarMarkers: any[] = []
        for (let i = 0; i < carDetailList.length; i++) {
          const { lnglat, directDegree, gpsStats, plateNumber } =
            carDetailList[i]
          const marker = new AMap.Marker({
            zIndex: 10,
            angle: directDegree,
            anchor: 'center',
            // map: AMapRef.current,
            position: lnglat,
            extData: {
              plateNumber,
              gpsStats
            }
          })
          marker.on('click', carMarkerClick)
          const iconInstance = _getCarMarkerIconInstance(gpsStats, currZoom)
          marker.setIcon(iconInstance)
          tempCarMarkers.push(marker)
        }
        carMarkersRef.current = tempCarMarkers
        const boundsMarkers = _getBoundingsMarkers(tempCarMarkers)

        AMapRef.current.add(boundsMarkers)
      } else {
        AMapRef.current.remove(carMarkersRef.current)
        const boundsMarkers = _getBoundingsMarkers(carMarkersRef.current)
        const newIconBoundsMarkers = boundsMarkers.map((markerInstance) => {
          const { gpsStats } = markerInstance.getExtData()
          const iconInstance = _getCarMarkerIconInstance(gpsStats, currZoom)
          markerInstance.setIcon(iconInstance)
          return markerInstance
        })

        AMapRef.current.add(newIconBoundsMarkers)
      }
    } else {
      AMapRef.current.remove(carMarkersRef.current)
    }

    // const markerOverlays = AMapRef.current.getAllOverlays('marker');
    // console.log('--获取marker覆盖物--markerOverlays--:', markerOverlays); //不包括可视化的点
  }

  function _loadOrgMarker(orgList: TCurrOrgAddressItem[]) {
    const currZoom = AMapRef.current.getZoom()
    if (currZoom >= 12 && currZoom < 21) {
      _loadOrgMarkerCommon(orgList)
    } else {
      AMapRef.current.remove(orgMarkersRef.current)
    }
  }

  //----新增数据分析接口----
  function _getDataAnalysis(
    dataAnalysisTypeParam: IDataAnalysisType,
    entIdParam: string
  ) {
    return getDataAnalysis({ entId: entIdParam, time: dataAnalysisTypeParam })
      .then((res) => {
        const { data = [] } = res
        setDataAnalysisList([...data])
        // console.log("--getDataAnalysis--data--:", data)
      })
      .catch((err) => {
        console.error('--BigScreenBase--getDataAnalysis--err--:', err)
      })
  }
  //新增数据分析切换
  const handleDataAnalysisTabChange = (activeTab: Tb) => {
    if (activeTab.value === dataAnalysisType) return
    clearTimer()
    const currType = activeTab.value as IDataAnalysisType
    setDataAnalysisType(currType)
    dataAnalysisTypeRef.current = currType
    _getDataAnalysis(currType, selectedAssociationItem.key).finally(() => {
      startTimer()
    })
  }

  //停止新增数据分析自动切换
  function clearDataAnalysInterval() {
    if (analysTypeIntervalRef.current) {
      clearInterval(analysTypeIntervalRef.current)
    }
  }

  //开始新增数据分析自动切换
  function startDataAnalysInterval() {
    if (analysTypeIntervalRef.current) {
      clearInterval(analysTypeIntervalRef.current)
      analysTypeIntervalRef.current = undefined
    }
    analysTypeIntervalRef.current = setInterval(() => {
      const currTypeIndex = analysTitleTab.findIndex(
        (listItem) => listItem.value === dataAnalysisTypeRef.current
      )
      let nextTypeIndex = 0
      if (currTypeIndex >= analysTitleTab.length - 1) {
        nextTypeIndex = 0
      } else {
        nextTypeIndex = currTypeIndex + 1
      }
      // console.log('--nextTypeIndex--dataAnalysisTypeRef.current---:', nextTypeIndex, dataAnalysisTypeRef.current)
      const currTypeItem = analysTitleTab[nextTypeIndex]
      if (!currTypeItem) {
        throw new Error('新增数据分析年月日切换未找到当前项')
      }
      const { value } = currTypeItem
      dataAnalysisTypeRef.current = value
      setDataAnalysisType(value)
      _getDataAnalysis(value, selectedAssociationItem.key)
    }, 60000)
  }

  //新增数据分析切换 MouseEnter
  const handleTitleTabMouseEnter: React.MouseEventHandler = (event) => {
    clearDataAnalysInterval()
  }

  //新增数据分析切换 MouseLeave
  const handleTitleTabMouseLeave: React.MouseEventHandler = (event) => {
    startDataAnalysInterval()
  }

  //设置车/组织pointLayer
  function _setPointLayer(type: 'car' | 'org') {
    // 创建数据源
    const pointGeo = new window.Loca.GeoJSONSource({
      data: {}
    })

    //创建点图层
    const pointLayer = new window.Loca.PointLayer({
      zooms: [5, 12], //图层缩放等级范围
      zIndex: 10,
      blend: 'normal' //lighter
      // opacity: "0.5"
    })

    //添加数据源
    pointLayer.setSource(pointGeo)

    //设置点样式
    pointLayer.setStyle({
      radius: 2.0,
      color: type === 'car' ? '#f66e2c' : '#40E6AE',
      borderWidth: 0,
      // borderColor: "#56E3FF",
      blurWidth: -1, //模糊半径，从哪个位置开始向边缘模糊。负数代表不进行模糊。
      unit: 'px'
      // opacity: 0.2  //没起作用
    })

    pointLayer.addAnimate({
      key: 'radius',
      value: [0, 1],
      duration: 500,
      easing: 'Linear',
      random: true, // 是否开启随机执行动画
      delay: 8000, // 随机动画延迟的时间段
      transform: 2000, // 随机动画的动画执行时间
      yoyo: true,
      repeat: 100000
    })
    return pointLayer
  }

  useEffect(() => {
    if (!largeScreenContainer.current || !containerWrapperRef.current) return
    isChoicingCarClusterRef.current = true //初始化完成后才能选择聚合/非聚合
    setChoicingCarCluster(true)
    _setWrapperSize(largeScreenContainer.current)

    _getDataAnalysis('half', entId).then(() => {
      //新增数据分析
      startDataAnalysInterval()
    })
    AMapLoader.load({
      key: import.meta.env.VITE_AMAP_APPKEY,
      version: '2.0',
      plugins: ['AMap.Weather', 'AMap.MarkerCluster', 'AMap.MassMarks'], //["AMap.Geocoder"],  //
      Loca: {
        //LOCAL数据可视化 是否加载 Loca， 缺省不加载
        version: '2.0.0' // Loca 版本，缺省 1.3.2
      }
    }).then((AMap) => {
      setViewloading(false)
      // 天气
      setWeatherPlugin(new AMap.Weather())

      const mapOptions: AMap.MapOptions = {
        zoom: 10, //, //[3,20]
        zooms: [5, 20], //中国地图，
        viewMode: '2D', //设置地图模式
        mapStyle: 'amap://styles/grey', //dark
        features: ['bg', 'point', 'road'], // 设置地图显示要素 ['bg', 'road', 'building', 'point']
        defaultCursor: 'default'
      }

      const map = new AMap.Map('carAndOrgMapContainer', mapOptions)

      AMapRef.current = map
      _setMapCenter(regionCode)
      // const bounds = map.getBounds();

      //为了弥补grey主题色的颜色不符合产品要求
      map.on('complete', () => {
        //启用地图范围限制
        const bounds = new AMap.Bounds(
          new AMap.LngLat(52.982575, 3.449744),
          new AMap.LngLat(160.358813, 57.048735)
        ) //西南角,东北角
        map.setLimitBounds(bounds) //getBounds：获取当前地图可视区域范围
        // console.log('触发地图资源加载完成事件');
        const amapLayersDom =
          containerWrapperRef.current!.getElementsByClassName('amap-layers')[0]
        const apmapMaskDom = amapLayersDom.getElementsByClassName(
          'carorg-amap-zh-mask'
        )[0]
        if (!apmapMaskDom) {
          const zhDiv = document.createElement('div')
          zhDiv.classList.add('carorg-amap-zh-mask')
          amapLayersDom.prepend(zhDiv)
        }
      })

      map.on('click', () => {
        if (carInfoWindowRef.current) {
          carInfoWindowRef.current.close()
        }
      })

      //监听地图缩放,初始化不会执行
      map.on('zoomend', () => {
        const currZoom = map.getZoom()
        // console.log('--zoomend--东北角--西南角--:', bounds.northEast.toString(), bounds.southWest.toString())
        // console.log("--zoomend--触发地图缩放结束时的事件--currZoom--:", currZoom)
        if (isCarClusterRef.current) {
          //聚合模式
          if (carDetailListRef.current.length) {
            _loadCarMarker(carDetailListRef.current, 'zoom')
            if (currZoom < 14 && carInfoWindowRef.current) {
              carInfoWindowRef.current.close()
            }
          }
          if (orgListRef.current.length) {
            _loadOrgMarker(orgListRef.current)
          }
        } else {
          if (carDetailListRef.current.length) {
            _laodCarMarkerForNoCluster(carDetailListRef.current)
          }

          if (orgListRef.current.length) {
            _laodOrgMarkerForNoCluster(orgListRef.current)
          }
        }
      })

      map.on('dragend', () => {
        // const bounds = map.getBounds();
        // console.log('--dragend--东北角--西南角--:', bounds.northEast.toString(), bounds.southWest.toString())
        const currZoom = map.getZoom()
        if (isCarClusterRef.current) {
          //聚合模式
          if (currZoom >= 14 && currZoom < 21 && carMarkersRef.current.length) {
            AMapRef.current.remove(carMarkersRef.current)
            const boundMarkers = _getBoundingsMarkers(carMarkersRef.current)
            // console.log("--dragend--boundMarkers.length--:", boundMarkers.length)
            AMapRef.current.add(boundMarkers)
          }
          //组织
          if (currZoom >= 12 && currZoom < 21 && orgMarkersRef.current.length) {
            AMapRef.current.remove(orgMarkersRef.current)
            const boundMarkers = _getBoundingsMarkers(orgMarkersRef.current)
            AMapRef.current.add(boundMarkers)
          }
        } else {
          if (carDetailListRef.current.length) {
            _laodCarMarkerForNoCluster(carDetailListRef.current)
          }
          if (orgListRef.current.length) {
            _laodOrgMarkerForNoCluster(orgListRef.current)
          }
        }
      })

      const loca = new window.Loca.Container({
        map
      })
      LocaRef.current = loca

      //-------省[5,12] 添加点图层-车、组织--------------
      const carPointLayer = _setPointLayer('car')
      carPointLayerRef.current = carPointLayer
      loca.add(carPointLayer) //添加图层

      const orgPointLayer = _setPointLayer('org')
      orgPointLayerRef.current = orgPointLayer
      loca.add(orgPointLayer)

      //-------市区...[9,20] 点聚合--------------
      _getCurrOrgCarList(entId, ['-1'], 'initial').finally(() => {
        // 当前协会车辆列表
        startTimer()
        isChoicingCarClusterRef.current = false
        setTimeout(() => {
          setChoicingCarCluster(false)
        }, 5000)
      })
      _getCurrOrgChildAddressList(entId, orgTypeRef.current)
    })

    return () => {
      clearTimer()
      clearDataAnalysInterval()
      if (LocaRef.current) {
        LocaRef.current.destroy()
        LocaRef.current = null
      }
      if (carInfoWindowRef.current) {
        carInfoWindowRef.current.destroy()
      }
      if (AMapRef.current) {
        AMapRef.current.destroy()
        AMapRef.current = null
      }
    }
  }, [])

  return (
    <div className="large-screen-container" ref={largeScreenContainer}>
      <ViewLoading show={viewLoading} />
      <div className="container-wrapper" ref={containerWrapperRef}>
        <div className="carorg-map-container" id="carAndOrgMapContainer"></div>
        {!viewLoading && (
          <>
            <ContentTsx.Provider
              value={{
                selectedAssociationItem,
                refreshFlag,
                startTimer,
                clearTimer
              }}
            >
              <WrapperHeader
                style={{
                  width: `${UIWIDTH}px`,
                  transform: `scale(${domScale})`
                }}
                selectedAssociationItem={selectedAssociationItem}
                onAssociationClick={handleAssociationClick}
                weatherPlugin={weatherPlugin}
                name="安全数据"
                prevTitle="治理成效"
                nextTitle="数智治理"
                gotoNext={() => {
                  setTimeout(() => {
                    navigator('/bigScreenWarn')
                  }, 500)
                  onSlideToLeft()
                }}
                gotoPrev={() => {
                  setTimeout(() => {
                    navigator('/bigScreenGovern')
                  }, 500)
                  onSlideToRight()
                }}
                isFullscreen={isFullscreen}
                onToggleFullScreen={toggleFullscreen}
              />
              <div
                className="wrapper-left-scale"
                style={{
                  left: `${8 * domScale}px`,
                  top: `${104 * domScale}px`,
                  transform: `scale(${domScale})`
                }}
              >
                <LargeScreenLeftContent
                  ref={LeftContentRef}
                ></LargeScreenLeftContent>
              </div>

              <div
                className="wrapper-center-section1"
                style={{
                  top: `${104 * domScale}px`,
                  left: `${478 * domScale}px`,
                  transform: `scale(${domScale})`
                }}
              >
                <OverviewBox
                  ref={OverviewBoxRef}
                  orgType={orgType}
                  onChoiceOrg={handleOrgTypeClick}
                />
              </div>

              <div
                className="wrapper-center-section2-scale"
                style={{
                  top: `${321 * domScale}px`,
                  right: `${478 * domScale}px`,
                  transform: `scale(${domScale})`
                }}
              >
                <Popover
                  content={carTypePopverContent}
                  overlayClassName="bigscreen-car-popover"
                  placement="bottomRight"
                  arrow={false}
                  trigger={['hover']}
                  getPopupContainer={() =>
                    containerWrapperRef.current as HTMLElement
                  }
                >
                  <div className="select-car">
                    <img className="select-img" src={carTransportSelectIcon} />
                    <p className="select-text">{carDropDownLableShow}</p>
                    <CaretDownOutlined
                      className="select-dropdown-icon"
                      onPointerEnterCapture={undefined}
                      onPointerLeaveCapture={undefined}
                    />
                  </div>
                </Popover>
                <div className="car-divider"></div>
                <div
                  className="car-cluster-choice"
                  onClick={carClusterOnChange}
                >
                  <div
                    className={classNames('choice-checkbox', {
                      ['checked']: !choicingCarCluster && isCarCluster,
                      ['disabled']: choicingCarCluster
                    })}
                  ></div>
                  <p className="choice-title">聚合数据</p>
                </div>
              </div>
              <div
                className="wrapper-center-section3-scale"
                style={{
                  bottom: `${16 * domScale}px`,
                  left: `${478 * domScale}px`,
                  transform: `scale(${domScale})`
                }}
              >
                <div className="bigscreen-module ms-module wrapper-center-section3 ">
                  <ModuleTitle
                    title={'新增数据分析'}
                    titleSectionOther={
                      <div className="section3-legend">
                        {echartsLegends.map((legend) => (
                          <>
                            <span
                              className="legend-color"
                              style={{ backgroundColor: legend.color }}
                            ></span>
                            <span className="legend-text">{legend.text}</span>
                          </>
                        ))}
                      </div>
                    }
                    activeKey={dataAnalysisType}
                    tab={analysTitleTab}
                    tabChange={handleDataAnalysisTabChange}
                    onTitleTabMouseEnter={handleTitleTabMouseEnter}
                    onTitleTabMouseLeave={handleTitleTabMouseLeave}
                  ></ModuleTitle>
                  <DataAnalysis
                    dataAnalysisList={dataAnalysisList}
                    ref={DataAnalysisCompRef}
                    dataAnalysisType={dataAnalysisType}
                  />
                </div>
              </div>
              <div
                className="wrapper-right-scale"
                style={{
                  right: `${8 * domScale}px`,
                  top: `${104 * domScale}px`,
                  transform: `scale(${domScale})`
                }}
              >
                <div className="wrapper-right">
                  <LargeScreenRightContent ref={RightContentRef} />
                </div>
              </div>
            </ContentTsx.Provider>
          </>
        )}
      </div>
    </div>
  )
}
